package com.piece.core.framework.util.location;

import com.alibaba.fastjson.JSONObject;
import com.piece.core.framework.support.response.AjaxResponse;
import com.piece.core.framework.util.net.HttpUtil;
import com.piece.core.framework.util.net.IpUtil;
import com.piece.core.framework.util.string.JsonUtil;
import com.piece.core.framework.util.basic.SpringUtil;
import com.piece.core.framework.util.string.StringUtil;
import com.piece.core.framework.properties.ApplicationProperties;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 获取地址工具类
 */
@Slf4j
@Setter
public class AddressUtil {

    private static final ReentrantLock lock = new ReentrantLock();

    private String url;

    private static AddressUtil instance;

    public static AddressUtil getInstance() {
        if (null == instance) {
            lock.lock();
            if (null == instance) {
                instance = new AddressUtil();
                ApplicationProperties properties = SpringUtil.getBean(ApplicationProperties.class);
                instance.setUrl(properties.getAddressUrl());
            }
            lock.unlock();
        }
        return instance;
    }

    public String getRealAddressByIP(String ip) {
        String address = "未查询到地址信息";

        // 内网ip转外网ip
        if (IpUtil.internalIp(ip)) {
            ip = IpUtil.getV4IP(ip);
        }
        Map<String, String> param = new HashMap<>();
        param.put("ip", ip);
        AjaxResponse result = HttpUtil.post(this.url).form(param).execute().response();
        if (null == result || StringUtil.isEmpty(result.getMsg())) {
            log.error("获取[{}]地理位置异常", ip);
            return address;
        }
        JSONObject jsonObject;
        try {
            jsonObject = JsonUtil.toBean(result.getMsg(), JSONObject.class);
            JSONObject data = jsonObject.getJSONObject("data");
            String region = data.getString("region");
            String city = data.getString("city");
            address = region + "," + city;
        } catch (Exception e) {
            log.error("获取[{}]地理位置异常: {}", ip, e.getMessage());
        }
        return address;
    }
}
